from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response, HttpResponse, HttpResponseRedirect
from django.template import RequestContext
from django.http import Http404

from apps.course.functions import course_reverse
from apps.management import Management
from models import *

import logging

logger = logging.getLogger('pet.apps.help.manage')

def FAQ_view(request, TheCourseParticipant, TheCourse):
	if (not request.user.is_superuser) and TheCourseParticipant.status != "INSTRUCTOR" and TheCourseParticipant.status != "ASSISTANT":
		raise Http404
	FAQ_Dict = {}
	FAQ_Subcategories = []
	FAQs = FAQ.find(course=TheCourse.course_id,include_admin=True)
	for faq in FAQs:
		categories = [item.strip() for item in faq.category.split(',')]
		for category in categories:
			subcategories = [item.strip() for item in category.split('.')]
			if len(subcategories) > 0:
				if not subcategories[0] in FAQ_Dict: FAQ_Dict[subcategories[0]] = {}
				if len(subcategories) > 1:
					if not subcategories[1] in FAQ_Dict[subcategories[0]]: FAQ_Dict[subcategories[0]][subcategories[1]] = []
					FAQ_Dict[subcategories[0]][subcategories[1]].append(faq)
				else:
					if not '__general' in FAQ_Dict[subcategories[0]]: FAQ_Dict[subcategories[0]]['__general'] = []
					FAQ_Dict[subcategories[0]]['__general'].append(faq)
	for category,subcategories in FAQ_Dict.items():
		for subcategory, list in subcategories.items():
			if not subcategory in FAQ_Subcategories: FAQ_Subcategories.append(subcategory)
			list.sort(key = lambda item: item.question_id)
	FAQ_Categories = sorted(FAQ_Dict.keys())
	return render_to_response('help/manage.html',{'FAQs':FAQ_Dict, 'Categories':FAQ_Categories, 'Subcategories':FAQ_Subcategories}, context_instance=RequestContext(request))
Management.register_interface("Help","INSTRUCTOR;ASSISTANT;SUPERUSER", "manage", FAQ_view)

def FAQ_popup(request, TheCourseParticipant, TheCourse, faqid):
	if (not request.user.is_superuser) and TheCourseParticipant.status != "INSTRUCTOR" and TheCourseParticipant.status != "ASSISTANT":
		raise Http404
	TheFAQ = FAQ.find_or_404(question_link=faqid,include_admin=True)
	Response = render_to_response('help/FAQ_popup.html',{'FAQ':TheFAQ}, context_instance=RequestContext(request))
	Response['Content-Type'] = "no-management:text/html"
	return Response
Management.register_interface("Help","INSTRUCTOR;ASSISTANT;SUPERUSER", "popup", FAQ_popup)

def edit(request, TheCourseParticipant, TheCourse, faqid=None):
	TheFAQ = None
	if faqid: TheFAQ = FAQ.find_or_404(question_link=faqid,include_admin=True)
	
	if request.method == 'POST':
		Form = FAQForm(request.POST, instance=TheFAQ)
		if Form.is_valid():
			if Form.has_changed():
				Form.save()
				if 'Save' in request.POST and request.POST['Save'] == 'SaveEdit':
					return HttpResponseRedirect(course_reverse('management',TheCourse.course_id,app='help', command='edit', arguments=Form.instance.question_link))                    
			else:
				logger.form_unchanged("FAQ Form unchanged")
			if 'Save' in request.POST and request.POST['Save'] == 'SaveReturn':
				return HttpResponseRedirect(course_reverse('management',TheCourse.course_id,app='help'))
		else:
			logger.debug("FAQ Form invalid")
	else:
		Form = FAQForm(instance=TheFAQ)
		
	return render_to_response('help/edit.html',{'form':Form,'TheFAQ':TheFAQ},context_instance=RequestContext(request))
Management.register_interface('Help','ASSISTANT;INSTRUCTOR;SUPERUSER','edit',edit)